package com.tim.javaApi.reflect.jdk;

import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Paths;

public class ProxyDemo {
    //被代理的类
    private static UserService userServiceImpl=new UserService.UserServiceImpl();

    public static void main(String[] args) throws IOException {
        //jdk1.8及之前版本使用这个 (我的是1.8,没试过其他版本)
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
        //新版本jdk使用这个
//        System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");

        //先实例一个ProxyFactory类
        ProxyFactory<UserService> proxyFactory=new ProxyFactory<>(userServiceImpl);
        //获取对应的UserService代理类，后面有查看代理类的方法
        UserService proxy =proxyFactory.getInstance();
        proxy.add();
        byte[] proxyClass = ProxyGenerator.generateProxyClass(proxy.getClass()
                .getSimpleName(), proxy.getClass().getInterfaces());
        //将字节码文件保存到D盘，文件名为$Proxy0.class
        FileOutputStream outputStream = new FileOutputStream(new File(
                "d:\\code\\"+proxy.getClass().getSimpleName()+".class"));
        outputStream.write(proxyClass);
        outputStream.flush();
        outputStream.close();
        Files.write(Paths.get("aaa"), new byte[]{1}, new OpenOption[0]);
    }

}
